package com.bw.apps.net

import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.bw.apps.net.entity.AppEntity
import com.bw.apps.net.entity.AppEntityState
import com.bw.apps.net.entity.AppMultipleEntity
import com.bw.common.mvi.BaseViewModel
import com.bw.network.download.DownloadManager
import com.bw.network.download.DownloadStatus
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import java.io.File
import java.util.HashMap

class NetAppsViewModel : BaseViewModel<NetAppsRepo,AppEntityState>() {

    private var page = 1

    override fun createRepo(): NetAppsRepo {return NetAppsRepo()}

    override fun createState(): AppEntityState {
        return AppEntityState(false,ArrayList(),false,false,false,DownloadStatus.Progress(0))
    }

    //请求应用列表
    fun selApps(userId:Int){
        val map = HashMap<String,Any>()
        map["userId"]=userId
        map["page"]=page
        viewModelScope.launch {
            repo.requestApps(map)
                .flowOn(Dispatchers.IO)
                .catch { t : Throwable->
                    LogUtils.e("errorMsg:${t.message}")  }
                .onStart { mutableContainer.updateRequestState { copy(request=true,complate = false) } }
                .onCompletion { mutableContainer.updateRequestState { copy(request=false,complate = true) } }
                .collect{
                    val entity = it as AppEntity
                    val list = ArrayList<AppMultipleEntity>()
                    entity.data.forEach {
                        val titleEntity = AppMultipleEntity(it.title,0,"","",0.0,
                            0,"",0,0,
                            true,true,"","","","","",
                            "","",NetAppsAdapter.TITLETYPE)
                        list.add(titleEntity)
                        var index = 0
                        while (index<it.appsList.size){
                            list.add(AppMultipleEntity("",it.appsList[index].appId,
                                it.appsList[index].appIcon,it.appsList[index].appName,
                                it.appsList[index].appSize, it.appsList[index].appUserId,
                                it.appsList[index].userName,it.appsList[index].uploadTime,
                                it.appsList[index].updateTime,it.appsList[index].operationFlag,
                                it.appsList[index].trustFlag,it.appsList[index].apkUrl,
                                it.appsList[index].appImgs,it.appsList[index].versionCode,
                                it.appsList[index].appIntroduction,it.appsList[index].updateStr,
                                it.appsList[index].netUrl,it.appsList[index].app_package,
                                NetAppsAdapter.VALUETYPE))
                            index ++
                        }
                    }
                    mutableContainer.updateUiState { copy(appsState=true , apps=list , downLoadState = false,
                        doneState = false, startState = false) }
                }
        }
    }

    //下载应用
    fun downloadApp(urlStr : String,path : String){
        viewModelScope.launch {
            DownloadManager.download(urlStr, File(path)).flowOn(Dispatchers.IO)
                .catch { t : Throwable->
                    LogUtils.e("errorMsg:${t.message}")  }
                .onStart {
                    mutableContainer.updateUiState {
                        copy(appsState=false,downLoadState = false, startState = true,
                            doneState = false) }
                }.collect{
                    if(it is DownloadStatus.Err){
                        mutableContainer.updateUiState {
                            copy(appsState=false,downLoadState = false,
                                startState = false,
                                doneState = true) }
                    }
                    if (it is DownloadStatus.Done)
                        mutableContainer.updateUiState {
                            copy(appsState=false,downLoadState = false,
                                startState = false,
                                doneState = true) }
                    if (it is DownloadStatus.Progress){
                        val prg : DownloadStatus.Progress = it
                        mutableContainer.updateUiState {
                            copy(appsState=false,downLoadState = true,
                                startState = false,
                                doneState = false,
                                downLoad = prg) }
                    }
                }
        }
    }
}